﻿using System.Linq;
using System.Web.Mvc;
using FlickrXplorer.Web.Models;
using FlickrXplorer.Web.Plugin;

namespace FlickrXplorer.Web.Controllers
{
  public class DebugController : Controller
  {
    public ActionResult Index(string message)
    {
      if (message != null)
      {
        return View("Index", new Message(message));
      }
      else
      {
        return View("Index");
      }
    }

    public ActionResult UpdatePluginStatus(string pluginId, PluginStatus newStatus)
    {
      // Find the plugin
      FlickrXplorerPlugin plugin = PluginManager.Current.Plugins.Where(p => p.Id == pluginId).FirstOrDefault();
      if (plugin != null)
      {
        plugin.PluginStatus = newStatus;
        return RedirectToAction("Index", 
         new { message = "'" + plugin.Name + "''s status has been updated to " + newStatus.ToString()});
      }
      else
      {
        return RedirectToAction("Index",
          new { Message = "There is no plugin with ID = '" + pluginId + "'." });
      }
    }

    public ActionResult UpdateSiteOptions(bool markAllPlugins)
    {
      PluginManager.Current.MarkAllPlugins = markAllPlugins;
      return RedirectToAction("Index",
        new { message = "The site options have been updated." });
    }

    public ActionResult RunPlugin(string pluginId,
      bool? showLoadingTime)
    {
      TestHarness harness = new TestHarness()
      {
        ShowLoadingTime = showLoadingTime.GetValueOrDefault()
      };

      // Find the plugin
      FlickrXplorerPlugin plugin = PluginManager.Current.Plugins.Where(p => p.Id == pluginId).FirstOrDefault();
      harness.Plugin = plugin;
      return View("RunPlugin", harness);
    }

    public ActionResult EnableAllPlugins()
    {
      PluginManager.Current.Plugins.Foreach((FlickrXplorerPlugin p) =>
      {
        p.PluginStatus = PluginStatus.Enabled;
      });
      return RedirectToAction("Index",
        new { message = "All plugins have been enabled." });
    }

    public ActionResult DisableAllPlugins()
    {
      PluginManager.Current.Plugins.Foreach((FlickrXplorerPlugin p) =>
        {
          p.PluginStatus = PluginStatus.Disabled;
        });
      return RedirectToAction("Index",
        new { message = "All plugins have been disabled." });
    }
  }
}
